package com.yiban.demo.Global.Entity;

import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * controller层方法统一返回值
 * 用于包装返回值，携带一些描述性信息
 * @param <T> 被包裹的类
 */
@Data
public class ResponseEntity<T>{
    private T responseBody;
    private Integer status;
    private String desc;

    public ResponseEntity(){}

    public ResponseEntity(T responseBody, int status, String desc) {
        this.responseBody = responseBody;
        this.status = status;
        this.desc = desc;
    }

    /**
     *
     * @param info 实际返回值
     * @param status 状态码
     * @param desc 描述性信息
     * @param <T> 被包裹的类
     * @return
     */
    public static<T> ResponseEntity<T> Success(T info, int status, String desc){
        return new ResponseEntity<>(info, status, desc);
    }

    /**
     *
     * @param info 实际返回值
     * @param status 状态值
     * @param <T> 被包裹的类
     * @return
     */
    public static<T> ResponseEntity<T> Success(T info,int status){
       return Success(info, status, "");
    }

    /**
     *
     * @param info 实际返回值
     * @param <T> 被包裹的类
     * @return 成功返回的status状态码默认为200;
     */
    public static<T> ResponseEntity<T> Success(T info){
        return Success(info, 200);
    }

    /**
     *
     * @param status 状态码
     * @param desc 错误信息描述
     * @param <T> 被包裹的类
     * @return
     */
    public static<T> ResponseEntity<T> Failure(int status,String desc){
        return new ResponseEntity<>(null, status, desc);
    }

    /**
     * 默认状态码为500
     * @param desc 错误信息描述
     * @param <T> 被包裹的类
     * @return
     */
    public static<T> ResponseEntity<T> Failure(String desc){
        return Failure(500, desc);
    }
    public static<T> ResponseEntity<T> Failure(String desc,Class<T> returnClass){
        return Failure(500, desc);
    }


    public static void writeBack(HttpServletResponse httpServletResponse,String msg){
        httpServletResponse.setContentType("text/plain; charset=utf-8");
        try(final PrintWriter writer = httpServletResponse.getWriter()) {
           writer.write(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
